import { Injectable } from "@nestjs/common";
import { PrismaClient } from "@prisma/client";
import configuration from "src/common/configuration";

const MASTER_INFORMATION = configuration.user?.master;
const ADMINISTRATORS = configuration.user?.administrators;

@Injectable()
export class UserService {
  constructor(private readonly prisma: PrismaClient) {}

  isMaster(nickname: string): boolean {
    return nickname === MASTER_INFORMATION?.nickname;
  }
  getMasterNickname(): string {
    return MASTER_INFORMATION?.nickname;
  }
  getMasterUsername(): string {
    return MASTER_INFORMATION?.username;
  }
  getMasterEmails(): string[] {
    return MASTER_INFORMATION?.emails;
  }

  isAdministrator(username: string): boolean {
    return ADMINISTRATORS?.includes(username);
  }

  async getUserEmailByID(id: number) {
    try {
      const user = await this.prisma.user.findUnique({
        select: {
          email: true,
        },
        where: {
          id,
        },
      });
      if (user) {
        return user.email;
      }
    } catch (e) {
      console.error(e);
      return null;
    }
    return null;
  }

  generateCode() {
    const CHARS = [
      "a",
      "b",
      "c",
      "d",
      "e",
      "f",
      "g",
      "h",
      "i",
      "j",
      "k",
      "l",
      "m",
      "o",
      "p",
      "q",
      "r",
      "s",
      "t",
      "u",
      "v",
      "w",
      "x",
      "y",
      "z",
      "0",
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
    ];
    let code = "";
    for (let i = 0; i < 6; i++) {
      const index = Math.floor(Math.random() * CHARS.length);
      code += CHARS[index];
    }
    return code;
  }
}
